package com.drama.outtake.controller;

import com.drama.outtake.MyException;
import com.drama.outtake.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Optional;

/**
 * @Author : 李先均
 * @Date 2023/3/5 19:44
 */
@RestController
@RequestMapping({"/file", "/profile/upload"})
@Slf4j
public class FileController {
    @Value("${file.upload-dir.avatar}")
    private String avatarUploadDir;
    @Value("${file.upload-dir.comment}")
    private String commentUploadDir;

    @PostMapping("/uploadAvatarPhotos")
    public Result<String> uploadAvatarPhotos(MultipartFile file) throws IOException {
        log.info("(post):/uploadFile/avatar");
        return uploadPhotos(file, avatarUploadDir);
    }

    @PostMapping("/uploadCommentPhotos")
    public Result<String> uploadCommentPhotos(MultipartFile file) throws IOException {
        return uploadPhotos(file, commentUploadDir);
    }

    private Result<String> uploadPhotos(MultipartFile file, String baseFilePath) throws IOException {
        if (file == null) {
            throw new MyException("文件上传错误");
        }
        String fileType = Optional.of(file)
                .map(MultipartFile::getContentType)
                .orElseThrow(() -> new MyException("文件上传错误"));
        if (!fileType.startsWith("image")) {
            throw new MyException("上传的文件类型错误");
        }
        String pathOfDate = LocalDate.now().toString().replace('-', '/');
        Path filePath = Paths.get("%s/%s".formatted(baseFilePath, pathOfDate), file.getOriginalFilename());
        Files.createDirectories(filePath.getParent());
//        Files.createFile(filePath);
        try {
            Files.write(filePath, file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("头像文件存储失败");
        }
        String filePathStr = filePath.toString()
                .replace("\\", "/")
                .replace("static/", "");
        return Result.ok("http://localhost:8890/" + filePathStr);
    }

    @GetMapping("/getAvatar/{fileName}")
    public ResponseEntity<Resource> downloadFile(@PathVariable("fileName") String fileName) throws IOException {
        log.info("(get):/file/getAvatar/fileName");
        File file = new File(avatarUploadDir, fileName);
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        MediaType mediaType;
        switch (fileName.split("\\.")[1]) {
            case "jpg":
            case "jpeg":
                mediaType = MediaType.IMAGE_JPEG;
                break;
            case "gif":
                mediaType = MediaType.IMAGE_GIF;
                break;
            case "png":
                mediaType = MediaType.IMAGE_PNG;
                break;
            default:
                throw new MyException("文件类型错误");
        }
        return ResponseEntity.ok()
                .contentLength(file.length())
                .contentType(mediaType)
                .body(resource);
    }
}
